<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\sj;
use DB;
class SjController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function getIndex()
    {
        //获取数据
       $sj = sj::get();

        $data = $this -> findSubTree($sj);

        return view('sj.sj',['data'=>$data]);
    }
    public function findSubTree($cates,$id=0,$lev=1)
    {

          $subtree = [];

          foreach ($cates as $v) {

            if($v -> pid == $id){

                $v -> lev = $lev;
                $subtree[] = $v;
                $subtree = array_merge($subtree,$this -> findSubTree($cates,$v->id,$lev+1));
            }
          }

          return $subtree;
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function getAdd()
    {
        $sj = sj::get();
        $data = $this -> tree($sj);
        return view('sj.index',['data' => $data]);
    }

    public function tree($cates,$id=0,$lev=0)
     {
       static $sub = [];
       foreach($cates as $v){
         if($v -> pid == $id){ 
           
           $v -> lev = $lev;
           $sub[] = $v;
           $this -> tree($cates,$v -> id,$lev+1);
         }            
       }
       return $sub;
     }
     /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function getCr(Request $request)
    {
        $res = DB::table('sjs')
                  ->insert(['area'=>$request->area,'pid'=>$request->pid]);

        if ($res) {
            return redirect('/sj/index');
        }else{
            return redirect('/sj/index');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
